package com.googlecode.moneyManager.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Author: Sergiy Doroshenko
 * Date: Jul 19, 2010
 * Time: 12:38:53 PM
 */
public class SpringApplicationContext implements ApplicationContextAware {

    private static ApplicationContext CONTEXT;
    private static String[] contextLocations = new String[]{"classpath:appContext.xml"};

    /**
     * This method is called from within the ApplicationContext once it is
     * done starting up, it will stick a reference to itself into this bean.
     *
     * @param context a reference to the ApplicationContext.
     */
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        CONTEXT = context;
    }

    public static ApplicationContext getCONTEXT() {
        if(CONTEXT == null){
            CONTEXT = new ClassPathXmlApplicationContext(contextLocations);
        }
        return CONTEXT;
    }

    public static void setContextLocation(String[] locations){
        contextLocations  = locations;
    }

    /**
     * This is about the same as context.getBean("beanName"), except it has its
     * own static handle to the Spring context, so calling this method statically
     * will give access to the beans by name in the Spring application context.
     * As in the context.getBean("beanName") call, the caller must cast to the
     * appropriate target class. If the bean does not exist, then a Runtime error
     * will be thrown.
     *
     * @param beanClass the class of the bean to get.
     * @return an Object reference to the named bean.
     */
    public static <T> T getBean(Class<T> beanClass) {
        return getCONTEXT().getBean(beanClass);
    }
    public static <T> T getBean(String beanName,Class<T> beanClass) {
        return getCONTEXT().getBean(beanName, beanClass);
    }


}

